package com.itlong.cloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.VO.app.AppTCPOpenDoorVO;
import com.itlong.cloud.POJO.VO.app.AppTCPResultVO;
import com.itlong.cloud.POJO.VO.property.CloudIntercomDeviceVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.dao.ICloudIntercomOrdersDao;
import com.itlong.cloud.network.tcp.socket.ScocketClient;
import com.itlong.cloud.service.ITCPService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <desc>
 * TCP业务相关service(实现开门和音视频切换)
 * </desc>
 *
 * @createDate 2018/09/12
 */
@Service
public class TCPServiceImpl implements ITCPService {
    private static final Logger LOG = LoggerFactory.getLogger(TCPServiceImpl.class);
    @Value("${" + PlatformConstants.TCP_REDIS_IP + "}")
    public String TCP_REDIS_IP;
    @Value("${" + PlatformConstants.TCP_REDIS_PORT + "}")
    public String TCP_REDIS_PORT;

    private static final String tcpRedisKey = "_heartbeat";

    private static final String tokenInfo = "abcdef";

    private static final String idle = "idle";//空闲时开门
    private static final String spy = "spy";//主动呼出被接听开门
    private static final String talk = "talk";//对方呼自己开门

    @Autowired
    ICloudIntercomOrdersDao iCloudIntercomOrdersDao;

    /**
     * <desc>
     * 发送消息到TCP服务(弃用)
     * </desc>
     *
     * @param userId 用户编号
     * @param sipAccount sip帐号
     * @param message    指令相关信息
     * @param cmdFlag    指令命令 10开门  11音视频切换
     * @return
     * @author Qiang.S
     * @createDate 2018/09/12
     */
    @Override
    public AppTCPResultVO sendMessage(String userId, String sipAccount, String message, int cmdFlag) {
        //返回值
        AppTCPResultVO appTCPResultVO = new AppTCPResultVO();
        appTCPResultVO.setDataFlag("1");
        appTCPResultVO.setVideoState("");
        Jedis redis = new Jedis(TCP_REDIS_IP, Integer.parseInt(TCP_REDIS_PORT));
        //sipAccount 获取设备 device_unique
        LOG.info("cmdFlag:" + cmdFlag);
        LOG.info("message:" + message);
        LOG.info("sipAccount:" + sipAccount);
        CloudIntercomDeviceVO intercomDevice = iCloudIntercomOrdersDao.getDeviceUniqueBySip(sipAccount);
        String systemType = null;
        String deviceUnique = null;
        if (sipAccount.length() == 13) {
            deviceUnique = sipAccount;
            systemType = iCloudIntercomOrdersDao.getSystemTypeByDeviceUnique(sipAccount);
        }else if (intercomDevice != null){
            deviceUnique = intercomDevice.getDeviceUnique();
            systemType = intercomDevice.getSystemType();
        }
        LOG.info("deviceUnique:" + deviceUnique);
        LOG.info("systemType:" + systemType);

        long TTL = redis.ttl(deviceUnique + tcpRedisKey);//获取缓存中设备的ttl判断是否为空
        LOG.info("TTL:" + TTL);
        if (TTL > 0L && deviceUnique != null && !"".equals(deviceUnique)) {
            Object deviceInfo = redis.get(deviceUnique + tcpRedisKey);
            LOG.info("deviceInfo:" + deviceInfo);
            if (deviceInfo != null && !"".equals(deviceInfo)) {
                Map<String, Object> map = JsonUtil.JsonToMap(deviceInfo.toString());
                String address = map.get("server_address").toString();//获取tcp地址
                String[] addressAll = address.split(",");
                if (addressAll.length == 2) {
                    addressAll[0] = addressAll[0].replace("[","").replace("\"","");//处理redis中IP
                    addressAll[1] = addressAll[1].replace("]","");//处理redis中端口
                    //Ver,Token,From,To,Cmd,Length,Body
                    String ver = StringHandlerUtil.intToHexString(1, 2);//版本号目前默认为1  2字节
                    String token = StringHandlerUtil.bytesToHexString(tokenInfo.getBytes());//token目前默认abcdef  6字节
                    //发起方使用uuid  40字节
                    String from = StringHandlerUtil.bytesToHexString((UUID.randomUUID().toString().replace("-", "").toLowerCase()).getBytes());
                    from = StringHandlerUtil.bytesToHexString(buildOpenDoorFrom(from).getBytes());
                    //接收方使用deviceUnique  40字节
                    String to = StringHandlerUtil.bytesToHexString(buildOpenDoorFrom(deviceUnique).getBytes());//40字节
                    String cmd = StringHandlerUtil.intToHexString(cmdFlag, 2);//指令:10开门,11音视频切换 2字节
                    String body = "";//不限制
                    String length = StringHandlerUtil.intToHexString(0, 4);//消息体长度默认为0  4个字节
                    if (cmdFlag == 10) {
                        String[] detail = message.split("-");
                        if (detail.length >= 3) {
                            List<String> list = new ArrayList<>();
                            for (int y = 3; y < detail.length; y++) {
                                list.add(detail[y]);
                            }
                            LOG.info("list:" + list);
                            AppTCPOpenDoorVO appTCPOpenDoorVO = new AppTCPOpenDoorVO();
                            appTCPOpenDoorVO.setNumOfRoom(Integer.parseInt(detail[2]));
                            LOG.info("detail[1]:" + detail[1]);
                            if (detail[1].equals(idle)) {//空闲时开门
                                appTCPOpenDoorVO.setOpenType(1);
                            }
                            if (detail[1].equals(spy)) {//主动呼出被接听开门
                                appTCPOpenDoorVO.setOpenType(3);
                            }
                            if (detail[1].equals(talk)) {//对方呼自己开门
                                appTCPOpenDoorVO.setOpenType(2);
                            }
                            appTCPOpenDoorVO.setRooms(list);
                            if ("2".equals(systemType)) {
                                appTCPOpenDoorVO.setUserId(userId);//安卓云对讲的时候传user_id
                            }
                            body = JSONObject.toJSONString(appTCPOpenDoorVO);
                            LOG.info("body:" + body);
                            length = StringHandlerUtil.intToHexString(body.length(), 4);//消息体长度  4个字节
                            body = StringHandlerUtil.bytesToHexString(body.getBytes());
                        }
                    }else if (cmdFlag == 11) {
                        JSONObject json = new JSONObject();
                        json.put("videoState",Integer.parseInt(message));
                        body = json.toString();
                        LOG.info("body:" + body);
                        length = StringHandlerUtil.intToHexString(body.length(), 4);//消息体长度  4个字节
                        body = StringHandlerUtil.bytesToHexString(body.getBytes());
                    }
                    String order = ver + token + from + to + cmd + length + body;
                    byte[] res = ScocketClient.sendSocket(addressAll[0], addressAll[1], StringHandlerUtil.hexStringToByteArray(order));//socket返回值
                    String realRes = StringHandlerUtil.bytesToHexString(res);
                    if (realRes != null) {
                        String result = realRes.substring(188,realRes.length());
                        LOG.info("result:" + result);
                        result = new String(StringHandlerUtil.hexStringToByteArray(result));//拿到结果集
                        Map<String, Object> resultMap = JsonUtil.JsonToMap(result);
                        LOG.info("tcp服务返回:" + resultMap);
                        if (resultMap.get("msgCode") != null && "0".equals(resultMap.get("msgCode").toString())) {
                            appTCPResultVO.setDataFlag("0");
                            if (resultMap.get("videoState") != null && !"".equals(resultMap.get("videoState"))) {
                                appTCPResultVO.setVideoState(resultMap.get("videoState").toString());
                            }
                        }
                    }
                }
            }
        }
        return appTCPResultVO;
    }

    /**
     * 数据补零40长度
     * @return
     */
    private String buildOpenDoorFrom(String str){
        byte[] strBytes = str.getBytes();
        int length=strBytes.length;
        byte[] bytes=new byte[40];
        System.arraycopy(strBytes,0,bytes,0,length<40?length:40);
        return new String (bytes);
    }
}